package com.qf.fmall2204.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.fmall2204.product.entity.ProductComments;
import com.qf.fmall2204.product.mapper.ProductCommentsMapper;
import com.qf.fmall2204.product.service.IProductCommentsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.fmall2204.user.entity.User;
import com.qf.fmall2204.user.mapper.UserMapper;
import com.qf.fmall2204.vo.CommontsCountResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品评价  服务实现类
 * </p>
 *
 * @author dong
 * @since 2023-04-23
 */
@Service
public class ProductCommentsServiceImpl extends ServiceImpl<ProductCommentsMapper, ProductComments> implements IProductCommentsService {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    UserMapper userMapper;

    /**
     * "pageCount": 3,
     * "count": 7,
     * "list": []
     */
    @Override
    public HashMap<String, Object> detailCommonts(Integer id, Integer pageNum, Integer limit) {

        // 创建mp的分页对象，传入当前页号，和页大小
        Page<ProductComments> page = new Page<>(pageNum, limit);
        this.page(page,new QueryWrapper<ProductComments>().eq("product_id",id));

        HashMap<String, Object> map = new HashMap<>();

        map.put("pageCount",page.getPages()); // 总页数
        map.put("count",page.getTotal()); // 总条数

        // 补全缺少的 user表中的数据
        List<ProductComments> data = page.getRecords();
        populateUserData(data);

        map.put("list",data); // 当前页的数据

        return map;
    }


    @Override
    public CommontsCountResultVo detailCommontscount(Integer id) {

        CommontsCountResultVo resultVo = new CommontsCountResultVo();

        //1. 好评数量
        // SELECT COUNT(*) FROM product_comments WHERE product_id=3 AND comm_type=1;
        long goodTotal = this.count(new QueryWrapper<ProductComments>().eq("product_id",id).eq("comm_type", 1));
        //2. 中评数量
        long midTotal = this.count(new QueryWrapper<ProductComments>().eq("product_id",id).eq("comm_type", 0));
        //3. 差评数量
        long badTotal = this.count(new QueryWrapper<ProductComments>().eq("product_id",id).eq("comm_type", -1));

        //4. 总评价数量
        long total = goodTotal + midTotal + badTotal;

        //5. 好评率
//        double percent = goodTotal*1.0 / total * 100;

        BigDecimal percent = BigDecimal.valueOf(goodTotal)
                .multiply(BigDecimal.valueOf(100))
                .divide(BigDecimal.valueOf(total), 2, RoundingMode.HALF_UP);

        resultVo.setGoodTotal(goodTotal);
        resultVo.setMidTotal(midTotal);
        resultVo.setBadTotal(badTotal);
        resultVo.setTotal(total);
        resultVo.setPercent(percent);

        return resultVo;
    }


    @Override
    public CommontsCountResultVo detailCommontscountBetter(Integer id) {

        //1. 查询该商品的所有评价信息
        List<ProductComments> productComments = this.list(new QueryWrapper<ProductComments>().eq("product_id", id));

        //2. 处理数据
        // SELECT comm_type,COUNT(*) FROM `product_comments` WHERE product_id = 3 GROUP BY comm_type;
        Map<Integer, Long> map = productComments.stream()
                .collect(Collectors.groupingBy(ProductComments::getCommType, Collectors.counting()));

        //1. 好评数量
        // SELECT COUNT(*) FROM product_comments WHERE product_id=3 AND comm_type=1;
        long goodTotal = map.get(1);
        //2. 中评数量
        long midTotal = map.get(0);
        //3. 差评数量
        long badTotal = map.get(-1);

        //4. 总评价数量
        long total = goodTotal + midTotal + badTotal;

        //5. 好评率
        BigDecimal percent = BigDecimal.valueOf(goodTotal)
                .multiply(BigDecimal.valueOf(100))
                .divide(BigDecimal.valueOf(total), 2, RoundingMode.HALF_UP);

        CommontsCountResultVo resultVo = new CommontsCountResultVo();
        resultVo.setGoodTotal(goodTotal);
        resultVo.setMidTotal(midTotal);
        resultVo.setBadTotal(badTotal);
        resultVo.setTotal(total);
        resultVo.setPercent(percent);

        return resultVo;

    }


    private void populateUserData(List<ProductComments> data) {

        //1. 查询评论信息中关联的所有用户信息
        // List<ProductComments> ==> List<用户ID>
        List<String> userIdList = data.stream().map(ProductComments::getUserId).collect(Collectors.toList());

        List<User> userList = userMapper.selectList(new QueryWrapper<User>().in("user_id", userIdList));

        //2. 处理数据
        // 需要一个map， key=userid, value=User对象
        Map<Integer, User> usermap = userList.stream().collect(Collectors.toMap(User::getUserId, user -> user));

        // 把user信息填充回 ProductComments对象
        for (ProductComments productComments : data) {

            String userId = productComments.getUserId();

            User user = usermap.get(Integer.valueOf(userId));
            productComments.setUsername(user.getUsername());
            productComments.setUserImg(user.getUserImg());
            productComments.setNickname(user.getNickname());

        }

    }
}
